﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.IO;

namespace HttpMultiThreadDownloadExample
{
    class CombineFiles
    {
        private bool downloadFinish;
        private HttpDownload[] d;
        private ListBox listbox;
        private string filename;
        public CombineFiles(HttpDownload[] d,ListBox l,string name)
        {
            listbox = l;
            this.d = d;
            filename = name;
        }

        public void Combine()
        {
            
            while (true)
            {
                downloadFinish = true;
                int count = d.Length;
                for (int i = 0; i < count;++i )
                {
                    if (!d[i].IsFinish)
                    {
                        downloadFinish = false;
                        Thread.Sleep(100);
                        break;
                    }
                }
                if (downloadFinish = true)
                {
                    break;
                }
            }

            AddStatus("下载完毕，开始合并文件");

            FileStream sourceFile;
            FileStream targetFile;
            int readfile;
            targetFile = new FileStream(filename, FileMode.Create);
            byte[] bytes = new byte[8192];
            for (int i = 0; i < d.Length;++i )
            {
                sourceFile = new FileStream(d[i].TaretFileName, FileMode.Open);
                while (true)
                {
                    readfile = sourceFile.Read(bytes, 0, bytes.Length);
                    if (readfile>0)
                    {
                        targetFile.Write(bytes, 0, readfile);
                    }
                    else
                    {
                        break;
                    }
                }
                sourceFile.Close();
            }
            targetFile.Close();
            for (int i = 0; i < d.Length;++i )
            {
                File.Delete(d[i].TaretFileName);
            }
            AddStatus("合并完毕");
            
        }

        private delegate void AddStatusDelege(string mes);
        private void AddStatus(string mes)
        {
            if (listbox.InvokeRequired)
            {
                AddStatusDelege d = AddStatus;
                listbox.Invoke(d, mes);
            }
            else
            {
                listbox.Items.Add(mes);
            }
        }
    }
}
